package com.chenyue.cm.match.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chenyue.cm.base.aop.Log;
import com.chenyue.cm.base.bean.PageVo;
import com.chenyue.cm.base.bean.Pageable;
import com.chenyue.cm.bean.Success;
import com.chenyue.cm.common.utils.RequestUtil;
import com.chenyue.cm.common.vo.Page;
import com.chenyue.cm.live.vo.LiveUser;
import com.chenyue.cm.match.domain.*;
import com.chenyue.cm.match.service.*;
import com.chenyue.cm.match.vo.MatchScore;
import com.chenyue.cm.match.vo.MatchScoreList;
import com.chenyue.cm.user.service.JdAppUserService;
import com.chenyue.cm.utils.PageInfoUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chenyue-cm
 * @date 2021-07-20
 */
@RestController
@RequestMapping("/jdMatchScoreRecord")
public class JdMatchScoreRecordController {

    private final JdMatchScoreRecordService jdMatchScoreRecordService;

    private final JdAppUserService jdAppUserService;

    private final JdMatchFormatService matchFormatService;

    private final JdMatchItemService matchItemService;

    private final JdMatchGroupService matchGroupService;

    private final JdMatchService matchService;

    private final JdMatchSignService matchSignService;

    private final JdMatchFormatMemberService matchFormatMemberService;

    private final JdMatchLiveUserService jdMatchLiveUserService;

    public JdMatchScoreRecordController(JdMatchScoreRecordService jdMatchScoreRecordService, JdAppUserService jdAppUserService, JdMatchFormatService matchFormatService, JdMatchItemService matchItemService, JdMatchGroupService matchGroupService, JdMatchService matchService, JdMatchSignService matchSignService, JdMatchFormatMemberService matchFormatMemberService, JdMatchLiveUserService jdMatchLiveUserService) {
        this.jdMatchScoreRecordService = jdMatchScoreRecordService;
        this.jdAppUserService = jdAppUserService;
        this.matchFormatService = matchFormatService;
        this.matchItemService = matchItemService;
        this.matchGroupService = matchGroupService;
        this.matchService = matchService;
        this.matchSignService = matchSignService;
        this.matchFormatMemberService = matchFormatMemberService;
        this.jdMatchLiveUserService = jdMatchLiveUserService;
    }

    @RequestMapping("/getList")
    public Success getList(HttpServletRequest request) {
        Pageable pageInfo = RequestUtil.getPageable(request);
        PageVo<JdMatchScoreRecord> result = jdMatchScoreRecordService.getPageBean(pageInfo, JdMatchScoreRecord.class);
        return Success.success(result);
    }

    /**
     * @param vo 插入实体
     * @return Success
     */
    @Log
    @RequestMapping("/save")
    public Success save(JdMatchScoreRecord vo) {
        boolean success = jdMatchScoreRecordService.save(vo);
        return success ? Success.success() : Success.error();
    }

    /**
     * @param vo      修改实体
     * @param request id
     * @return Success
     */
    @Log
    @RequestMapping("/edit")
    public Success edit(JdMatchScoreRecord vo, HttpServletRequest request) {
        String id = request.getParameter("id");
        if (StringUtils.isNotBlank(id)) {
            int success = jdMatchScoreRecordService.getBaseMapper().updateById(vo);
            return success > 0 ? Success.success() : Success.error();
        } else {
            return Success.error("id不能为空");
        }
    }

    /**
     * @param id 主键
     * @return Success
     */
    @Log
    @RequestMapping("/delete/{id}")
    public Success deleteByPrimaryKey(@PathVariable("id") Integer id) {
        JdMatchScoreRecordExample aExample = new JdMatchScoreRecordExample();
        aExample.createCriteria().andIdEqualTo(id);
        int success = jdMatchScoreRecordService.deleteByExample(aExample);
        return success > 0 ? Success.success() : Success.error();
    }

    /**
     * 【API】----  删除多个数据
     *
     * @return Success
     */
    @Log
    @RequestMapping("/delete")
    public Success delete(String ids) {
        String[] idStrings = ids.split(",");
        for (String idString : idStrings) {
            int success = jdMatchScoreRecordService.deleteByPrimaryKey(idString);
            if (success == 0) {
                return Success.error();
            }
        }
        return Success.success();
    }


    @RequestMapping("/getScoreList")
    public Success getScoreList(HttpServletRequest request) {
        Pageable pageInfo = RequestUtil.getPageable(request);
        String formatId = request.getParameter("formatId");
        JdMatchFormat format = matchFormatService.getById(formatId);
        JdMatch match = matchService.getById(format.getMatchId());
        Long total = jdMatchLiveUserService.getMatchScoreListCount(Integer.parseInt(formatId));
        Page<List<MatchScore>> result = new Page<>(pageInfo.getPageIndex(), pageInfo.getPageSize(), total.intValue());
        List<MatchScore> matchScoreList = jdMatchLiveUserService.getMatchScoreList(Integer.parseInt(formatId),pageInfo.getPageIndex(),pageInfo.getPageSize());
        if(matchScoreList != null && matchScoreList.size()>0){
            for (MatchScore matchScore : matchScoreList) {
                if(2 == match.getMatchGroup()){
                    if(matchScore.getGroupId() != null){
                        matchScore.setGroupName(matchScore.getGroupId() == 0 ? "白名单" : matchGroupService.getById(matchScore.getGroupId()).getName());
                    }
                }
                if(matchScore.getScore() == null){
                    matchScore.setScore(0);
                }
            }
        }

        result.setContent(matchScoreList);
        return Success.success(result);
    }

    @PostMapping("/handlePromotion")
    @ApiOperation("手动晋级")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id", name = "userId", dataType = "integer", required = true),
            @ApiImplicitParam(value = "赛程id", name = "formatId", dataType = "integer", required = true),
            @ApiImplicitParam(value = "1晋级2淘汰", name = "state", dataType = "integer", required = true),
            @ApiImplicitParam(value = "当前赛程阶段 1初2复3决", name = "arrangeOrder", dataType = "integer", required = true),
            @ApiImplicitParam(value = "赛事id", name = "matchId", dataType = "integer", required = true),
    })
    public Success<String> handlePromotion(
            Integer userId, Integer formatId, Integer state, Integer arrangeOrder, Integer matchId
    ) {
        final JdMatchFormatMember one = matchFormatMemberService.lambdaQuery()
                .eq(JdMatchFormatMember::getUserId, userId)
                .eq(JdMatchFormatMember::getFormatId, formatId).one();
        if (one.getPromotionState() != null && one.getPromotionState() > 0) {
            return Success.error("已设置晋级状态");
        }
//            设置晋级生成排名
        one.setPromotionState(state);
        matchFormatMemberService.updateById(one);
//        不到决赛and设置=晋级
        if (arrangeOrder < 3 && state == 1) {
//            晋级到下一个赛程
            JdMatchFormatMember two = new JdMatchFormatMember();
            two.setUserId(one.getUserId());
            final JdMatchFormat format = matchFormatService.lambdaQuery()
                    .eq(JdMatchFormat::getArrangeOrder, arrangeOrder + 1)
                    .eq(JdMatchFormat::getMatchId, matchId).one();
            if (format == null) {
                return Success.error("赛程设置缺失");
            }
            two.setFormatId(format.getId());
            two.setGroupId(one.getGroupId());
            matchFormatMemberService.save(two);
        }
        return Success.success();
    }
}
